package ExperimentSix.SplitFile;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.atomic.AtomicInteger;

public class FileUploadServer {

    public static void main(String[] args) throws IOException {
        int serverPort = 62483;
        String outputFilePath = "E:\\Java\\JavaExperimentOne\\server_received_file.txt"; // 输出文件路径，请替换为实际路径
        AtomicInteger totalChunks = new AtomicInteger(0); // 使用AtomicInteger来安全地更新已接收分片数
        int expectedChunks = 0; // 预期的分片总数，此处需从客户端或其他方式获取

        try (ServerSocket serverSocket = new ServerSocket(serverPort)) {
            System.out.println("Server is listening on port " + serverPort);

            while (true) {
                try (Socket clientSocket = serverSocket.accept();
                     InputStream is = clientSocket.getInputStream()) {

                    DataInputStream dis = new DataInputStream(is);
                    int chunkNumber = dis.readInt(); // 读取分片编号
                    int dataSize = dis.readInt(); // 读取数据大小
                    byte[] data = new byte[dataSize];
                    dis.readFully(data); // 读取数据

                    Files.write(Paths.get(outputFilePath), data, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
                    System.out.println("分片 " + chunkNumber + " 被接收.");
                    // 增加已接收分片计数
                    int currentChunks = totalChunks.incrementAndGet();

                    // 检查是否所有分片都已接收
                    if (currentChunks == expectedChunks) {
                        System.out.println("所有分片都被接受.");
                        // 在这里可以添加合并文件后的处理逻辑，如验证文件完整性、执行后续操作等
                        break; // 所有分片接收完毕，跳出循环
                    }
                } catch (IOException e) {
                    System.err.println("Server error: " + e.getMessage());
                }
            }
        }
    }
}